cmake_minimum_required(VERSION 3.21)
project(work C)

set(CMAKE_C_STANDARD 99)

file(GLOB_RECURSE SOURCE_FILE "${PROJECT_SOURCE_DIR}/*.c" "${PROJECT_SOURCE_DIR}/*.h") #获取所有的.h和.c

#排除掉对应的源文件 例如一些测试文件的
set(EXCLUDE_DIRS)
foreach (EXCLUDE_DIR ${EXCLUDE_DIRS})
    file(GLOB_RECURSE REMOVE_SOURCE_FILE_TMP "${EXCLUDE_DIR}/*.c" "${EXCLUDE_DIR}/*.h")
    list(APPEND REMOVE_SOURCE_FILE ${REMOVE_SOURCE_FILE_TMP})
endforeach ()

list(REMOVE_ITEM SOURCE_FILE ${REMOVE_SOURCE_FILE})

set(ALL_INCLUDE_DIR)
foreach (FILE ${SOURCE_FILE}) #获得带有头文件的目录 所有层级 因为项目引入头文件不规范 有的是相对路径
    string(FIND ${FILE} ".h" index REVERSE)
    if (${index} EQUAL -1)
        continue()
    endif ()
    set(CUR_PATH ${FILE})
    while (1)
        string(FIND ${CUR_PATH} "/" index REVERSE)
        if (${index} EQUAL -1)
            break()
        endif ()
        string(SUBSTRING "${CUR_PATH}" 0 ${index} CUR_PATH)
        if (${CUR_PATH} STRLESS_EQUAL ${PROJECT_SOURCE_DIR})
            break()
        endif ()
        list(APPEND ALL_INCLUDE_DIR ${CUR_PATH})
    endwhile ()
endforeach ()

list(SORT ALL_INCLUDE_DIR COMPARE NATURAL ORDER DESCENDING) # 排序
list(REMOVE_DUPLICATES ALL_INCLUDE_DIR) #去重

foreach (INCLUDE_DIR ${ALL_INCLUDE_DIR})
    message(${INCLUDE_DIR})
endforeach ()

include_directories(${ALL_INCLUDE_DIR})
add_executable(${PROJECT_NAME} ${SOURCE_FILE})

